import subprocess
import configparser
import os
import sys
from pathlib import Path

# 读取配置文件获取数据库信息
cf = configparser.ConfigParser()
cf.read('resource.ini')
dbname = "mysql"
host = cf.get(dbname, dbname + "_" + "host")
port = cf.getint(dbname, dbname + "_" + "port")
user = cf.get(dbname, dbname + "_" + "user")
passwd = cf.get(dbname, dbname + "_" + "password")
db = cf.get(dbname, dbname + "_" + "database")

# 设置要生成的表名
tables = "in_inf_idp_bnd_info_di,factors,s02_bnd_ibsettlementquote,s07_bnd_cbondcf,s07_bnd_valuation,s07_bnd_basicinfo_realtime"

# 输出文件路径
output_file = Path(os.path.dirname(os.path.abspath(__file__))) / "peeweemodels.py"

# 构建命令参数列表
cmd_args = [
    sys.executable,  # 当前Python解释器路径
    "-m", "pwiz",
    "-e", "mysql",
    "-u", user,
    "-p", str(port),
    "-H", host,
    "-P", passwd,  # 注意密码直接通过命令行参数传递可能不安全
    "-t", tables,
    db
]

print(f"执行命令: {' '.join(cmd_args)}")

try:
    # 使用列表形式的参数而不是字符串，这样避免了命令行解析问题
    with open(output_file, 'w') as f:
        result = subprocess.run(cmd_args, stdout=f, text=True, check=True)
    print(f"成功生成模型文件: {output_file}")
    print(f"命令执行状态: {result.returncode}")
except subprocess.CalledProcessError as e:
    print(f"命令执行失败，错误码: {e.returncode}")
    print(f"错误信息: {e.stderr if hasattr(e, 'stderr') else '无详细错误信息'}")
except Exception as e:
    print(f"发生异常: {str(e)}")
